import paper from 'paper'

const local = {
  path: null,
}

const onMouseMove = (event) => {
  if (local.path) {
    if (local.path.segments.length > 1) {
      local.path.segments[local.path.segments.length - 1].remove()
    }
    local.path.add(event.point)
    const p1 = globalToLocal(local.path.segments[0].point)
    const p2 = globalToLocal(local.path.segments[1].point)
    let v = Math.sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y))
    tool.rulerValue = v
  }
}

const onMouseDown = (event) => {
  console.log(local.path)
  if (!local.path) {
    local.path = new paper.Path()
    local.path.strokeColor = 'Cyan'
    local.path.strokeWidth = 2
    local.path.strokeScaling = false
    local.path.add(event.point)
    console.log(local.path)
  } else {
    local.path.remove()
    local.path = null
  }
}

const onMouseDrag = (event) => {
  if (event.event.buttons == 2) {
    if (paper.project.activeLayer.rasterLayer) {
      paper.project.activeLayer.rasterLayer.position.x += event.delta.x
      paper.project.activeLayer.rasterLayer.position.y += event.delta.y
      paper.project.activeLayer.position.x += event.delta.x
      paper.project.activeLayer.position.y += event.delta.y
      local.isDraged = true
    }
  }
}

const onMouseUp = (event) => {}

const onToggleIn = () => {}
const onToggleOut = () => {}

function globalToLocal(point) {
  return paper.project.activeLayer.rasterLayer.globalToLocal(point)
}

export const tool = new paper.Tool()
tool.onMouseDown = onMouseDown
tool.onMouseDrag = onMouseDrag
tool.onMouseUp = onMouseUp
tool.onMouseMove = onMouseMove
tool.onToggleIn = onToggleIn
tool.onToggleOut = onToggleOut
tool.name = 'ruler'
tool.rulerValue = 0
